<template>
  <view class="team-page">
    <!-- 顶部背景 -->
    <view class="team-header" :style="{ backgroundImage: `url(${backgroundImages.header})` }">
      <image class="header-bg" src="/static/Images/team/Hader.png" mode="widthFix"></image>
      <view class="header-content">
        <view class="back-btn" @click="navigateBack">
          <image class="back-icon" src="/static/Images/team/Fanhui.png" mode="aspectFit"></image>
        </view>
        <view class="title">我的团队</view>
      </view>
          
    <!-- 收益卡片 -->
      <view class="team-card">
        <view class="card-row">
          <view class="card-column">
            <view class="card-label">可提现收益</view>
            <view class="card-amount">¥{{ formatCurrency(expectedIncome) }}</view>
          </view>
          <view class="card-column">
            <view class="card-label">已提现收益</view>
            <view class="card-amount">¥{{ formatCurrency(settledIncome) }}</view>
          </view>
        </view>
        <view class="card-notice">
          <view class="notice-icon"></view>
          <view class="notice-text">总收益: {{ formatCurrency(totalIncome) }}</view>
        </view>
      </view>
    </view>

    <!-- 数据统计 -->
    <view class="stats-container">
      <view class="stats-item-on" @click="navigateToPromotions" :style="{ backgroundImage: `url(${backgroundImages.promotion})` }">
        <view class="stats-content">
          <view class="stats-label">推广团队</view>
          <view class="stats-more">查看明细 ></view>
        </view>
      </view>
      
      <view class="stats-item-to" @click="navigateToCommission" :style="{ backgroundImage: `url(${backgroundImages.commission})` }">
        <view class="stats-content">
          <view class="stats-label">佣金明细</view>
          <view class="stats-more">查看明细 ></view>
        </view>
      </view>
    </view>
    
    <!-- 团队成员 -->
    <view class="team-section">
      <view class="section-title">隶属团队</view>
      <view class="member-item">
        <image class="member-avatar" :src="memberAvatar" mode="aspectFit" @error="onAvatarError"></image>
        <view class="member-info">
          <view class="member-name">{{ memberNickname }}</view>
          <view class="member-id">推荐人ID: {{ memberUid }}</view>
          <view class="member-time">加入时间: {{ memberJoinTime }}</view>
        </view>
      </view>
    </view>
    
    <!-- 邀请码部分 -->
    <view class="invite-section">
      <image class="invite-bg" src="/static/Images/team/Beijing.png" mode="widthFix"></image>
      <view class="invite-content">
        <view class="invite-code-container">
          <view class="invite-code">邀请码:{{ inviteCode }}</view>
          <view class="copy-btn" @click="copyInviteCode">
            <image class="copy-icon" src="/static/Images/team/Fuzhi.png" mode="aspectFit"></image>
            <text>复制</text>
          </view>
        </view>
        <view class="qrcode-container">
          <image class="qrcode" :src="qrcodeSrc" mode="aspectFit"></image>
        </view>
        <view class="share-btn" @click="shareInviteCode">长按保存二维码</view>
      </view>
    </view>
    
    <!-- 悬浮分享按钮 -->
    <view class="floating-share-btn" @click="shareInviteCode">
      <image class="floating-share-icon" src="/static/Images/team/Fenxiang.png" mode="aspectFit"></image>
    </view>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { userStorage } from '@/utils/storage';
import defaultAvatar from '/static/Images/touxiang/1.png';
import { userApi } from '@/utils/api';
import { getImageUrl } from '@/config/api';
import QRCode from 'qrcode';

// 成员信息（从上个页面传参而来）
const memberAvatar = ref(defaultAvatar);
const memberNickname = ref('昵称');
const memberUid = ref('');

// 清理头像 URL（去除可能的反引号/引号和首尾空白）
const normalizeUrl = (url) => {
  if (typeof url !== 'string') return '';
  const trimmed = url.trim();
  // 去除包裹的反引号/单引号/双引号
  return trimmed.replace(/^([`'"])(.*)\1$/, '$2');
};

// 判断头像是否无效
const isInvalidAvatar = (url) => {
  if (!url) return true;
  const lower = String(url).toLowerCase();
  if (lower === 'null' || lower === 'undefined') return true;
  return false;
};

// 图片加载失败回退
const onAvatarError = () => {
  memberAvatar.value = defaultAvatar;
};

// 接收路由参数并渲染
onLoad(async (options) => {
  // 未登录则跳转登录页
  if (!userStorage.isLoggedIn()) {
    uni.navigateTo({ url: '/pages/login/login' });
    return;
  }
  try {
    // 1) 获取用户信息（用于收益、sno、加入时间等）
    const resInfo = await userApi.getUserInfo();
    const data = (resInfo && (resInfo.data?.data ?? resInfo.data ?? resInfo)) || {};

    const bal = Number(data.balance ?? 0);
    const unbal = Number(data.unbalance ?? 0);
    expectedIncome.value = bal;
    settledIncome.value = unbal;
    totalIncome.value = bal + unbal;

    // 用户自己的加入时间
    const joinTs = data.create_time ?? '';
    memberJoinTime.value = formatTimestamp(joinTs) || '';

    // sno 与注册链接/二维码
    const sno = data.sno || '';
    inviteCode.value = sno;
    const origin = (typeof window !== 'undefined' && window.location && window.location.origin) ? window.location.origin : '';
    const path = '/pages/login/register?sno=' + encodeURIComponent(sno || '');
    registerUrl.value = origin + path;
    try {
      // 使用前端库生成二维码 dataURL
      qrcodeSrc.value = await QRCode.toDataURL(registerUrl.value, { width: 260, margin: 1 });
    } catch (e) {
      // 兜底：使用在线服务生成二维码图片
      qrcodeSrc.value = 'https://site.shixiaoquan.com' + path;
    }

    // 2) 获取团队列表（type=3，取一条）
    const resTeam = await userApi.myTeamList(1, 1, 3);
    const tdata = (resTeam && (resTeam.data?.data ?? resTeam.data ?? resTeam)) || {};
    const list = Array.isArray(tdata.list) ? tdata.list : (Array.isArray(tdata) ? tdata : (Array.isArray(tdata.data) ? tdata.data : []));
    const first = list[0] || {};

    // 昵称：nick_name 优先
    memberNickname.value = first.nick_name || first.nickname || memberNickname.value || '昵称';
    // 所属推荐人ID：id
    if (first.id != null) memberUid.value = String(first.id);

    // 头像（可选）
    if (first.avatar) {
      const normalized = normalizeUrl(first.avatar);
      memberAvatar.value = isInvalidAvatar(normalized) ? defaultAvatar : normalized;
    } else if (!memberAvatar.value) {
      memberAvatar.value = defaultAvatar;
    }
  } catch (e) {
    console.error('加载团队页数据失败: ', e);
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  }
});

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 加入时间、推荐码、注册链接与二维码
const memberJoinTime = ref('');
const inviteCode = ref(''); // userinfo.sno
const registerUrl = ref('');
const qrcodeSrc = ref('');
// 新增：收益相关
const totalIncome = ref(0);
const settledIncome = ref(0);
const expectedIncome = ref(0);

// 格式化时间戳（兼容 秒/毫秒/字符串）
const formatTimestamp = (ts) => {
  if (!ts) return '';
  let date;

  if (typeof ts === 'number') {
    const ms = ts > 1e12 ? ts : ts * 1000;
    date = new Date(ms);
  } else if (typeof ts === 'string') {
    const s = ts.trim();
    if (!s) return '';
    if (/^\d+$/.test(s)) {
      const num = Number(s);
      const ms = num > 1e12 ? num : num * 1000;
      date = new Date(ms);
    } else {
      // 兼容 'YYYY-MM-DD HH:mm:ss' 以及 ISO 字符串
      const normalized = (s.includes('T') || s.includes('Z')) ? s : s.replace(/-/g, '/');
      date = new Date(normalized);
    }
  } else {
    return '';
  }

  if (isNaN(date.getTime())) {
    // 无法解析时返回原始字符串，避免 NaN 展示
    return typeof ts === 'string' ? ts : '';
  }
  const pad = (n) => String(n).padStart(2, '0');
  const y = date.getFullYear();
  const m = pad(date.getMonth() + 1);
  const d = pad(date.getDate());
  const hh = pad(date.getHours());
  const mm = pad(date.getMinutes());
  const ss = pad(date.getSeconds());
  return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
};

// 金额格式化（保留两位小数）
const formatCurrency = (n) => {
  const num = Number(n);
  if (Number.isNaN(num)) return '0.00';
  return num.toFixed(2);
};

// 导航到推广明细
const navigateToPromotions = () => {
  uni.navigateTo({
    url: '/pages/team/teamlist'
  });
};

// 导航到佣金明细
const navigateToCommission = () => {
  uni.navigateTo({
    url: '/pages/wallet/commission'
  });
};

// 复制邀请码/注册链接
const copyInviteCode = () => {
  const text = registerUrl.value || '';
  if (!text) {
    uni.showToast({ title: '暂无可复制的地址', icon: 'none' });
    return;
  }
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({ title: '注册链接已复制', icon: 'success' });
    }
  });
};

// 背景图片计算属性
const backgroundImages = computed(() => ({
  header: getImageUrl('/static/Images/team/Toubu.png'),
  promotion: getImageUrl('/static/Images/team/Svip.png'),
  commission: getImageUrl('/static/Images/team/Wallet.png')
}));

// 分享邀请码
const shareInviteCode = () => {
  // 显示分享弹窗
  uni.showActionSheet({
    itemList: ['分享到微信', '分享到朋友圈', '复制链接', '保存图片'],
    success: (res) => {
      switch(res.tapIndex) {
        case 0: // 分享到微信
          uni.showToast({ title: '分享到微信功能开发中', icon: 'none' });
          break;
        case 1: // 分享到朋友圈
          uni.showToast({ title: '分享到朋友圈功能开发中', icon: 'none' });
          break;
        case 2: // 复制链接
          {
            const text = registerUrl.value || '';
            if (!text) {
              uni.showToast({ title: '暂无可复制的地址', icon: 'none' });
              return;
            }
            uni.setClipboardData({
              data: text,
              success: () => {
                uni.showToast({ title: '链接已复制', icon: 'success' });
              }
            });
          }
          break;
        case 3: // 保存图片
          uni.showToast({ title: '长按图片可保存', icon: 'none' });
          break;
      }
    }
  });
};
</script>

<style lang="scss">
.team-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 顶部背景 */
.team-header {
  position: relative;
  width: 100%;
  height: 17.5rem;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  padding-top: 80rpx;
  padding-left: 30rpx;
  padding-right: 30rpx;
  justify-content: space-between;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  color: #fff;
  font-size: 36rpx;
  font-weight: 500;
  flex: 1;
  text-align: center;
  margin-right: 60rpx; /* 为了平衡左侧返回按钮的宽度 */
}

/* 收益卡片 */
.team-card {
  margin: -40rpx 30rpx 30rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 3;
  margin-top: 4rem;
}

.card-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.card-column {
  flex: 1;
}

.card-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.card-amount {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.card-notice {
  display: flex;
  align-items: center;
  background-color: #fff5f5;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
}

.notice-icon {
  color: #ff4d4f;
  font-size: 28rpx;
  margin-right: 10rpx;
}

.notice-text {
  color: #ff4d4f;
  font-size: 28rpx;
}

/* 数据统计 */
.stats-container {
  display: flex;
  justify-content: space-between;
  margin: 30rpx 30rpx;
}

.stats-item-on {
  flex: 1;
  border-radius: 20rpx;
  padding: 20rpx;
  margin: 0 10rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.stats-item-to {
  flex: 1;
  border-radius: 20rpx;
  padding: 20rpx;
  margin: 0 10rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

.stats-item:first-child {
  margin-left: 0;
}

.stats-item:last-child {
  margin-right: 0;
}

.stats-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.stats-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.stats-label {
  font-size: 28rpx;
  color: #666;
}

.stats-more {
  font-size: 24rpx;
  color: #999;
}

.stats-icon {
  width: 80rpx;
  height: 80rpx;
}

.stats-icon-promotion {
  /* 推广人数图标的特定样式 */
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

.stats-icon-commission {
  /* 佣金明细图标的特定样式 */
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

/* 团队成员 */
.team-section {
  margin: 0 30rpx 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.member-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.member-info {
  flex: 1;
}

.member-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 10rpx;
}

.member-id {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 6rpx;
}

.member-time {
  font-size: 24rpx;
  color: #999;
}

/* 邀请码部分 */
.invite-section {
  margin: 0 30rpx 30rpx;
  position: relative;
  border-radius: 20rpx;
  overflow: hidden;
  height: 85vh;
}

.invite-bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

.invite-content {
  position: relative;
  z-index: 2;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.invite-title {
  font-size: 32rpx;
  color: #ff9500;
  font-weight: 500;
  margin-bottom: 30rpx;
  margin-top: 30rpx;
}

.invite-code-container {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    border-radius: 2rem;
    height: 3rem;
    width: 18rem;
    justify-content: space-evenly;
    margin-top: 31vh;
}

.invite-code {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-right: 20rpx;
  width: 20rem;
  padding-left: 1rem;
}

.copy-btn {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 6rpx 16rpx;
  border-radius: 30rpx;
  color: #000;
  font-size: 24rpx;
  margin-left: 5rem;
  width: 10rem;
}

.copy-icon {
  width: 30rpx;
  height: 30rpx;
  margin-right: 6rpx;
}

.qrcode-container {
  width: 300rpx;
  height: 300rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
  margin-top: 9vh;
}

.qrcode {
  width: 260rpx;
  height: 260rpx;
  
}

.share-btn {
  color: #fff;
  font-size: 30rpx;
  background-color: transparent;
  border: none;
  margin-top: 5.2vh;
  padding: 0;
  box-shadow: none;
  outline: none;
  text-align: center;
  display: inline-block;
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

/* 悬浮分享按钮 */
.floating-share-btn {
  position: fixed;
  right: 30rpx;
  bottom: 200rpx;
  width: 100rpx;
  height: 100rpx;
  background-color: #ff9500;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
  z-index: 100;
}

.floating-share-icon {
  width: 60rpx;
  height: 60rpx;
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
}
</style>